﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Controls.Controls;
using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Windows.Data;
using WPFExcelReport.Helpers;
using System.Data.OracleClient;
using System.Windows.Controls;
using System.Windows;
namespace WPFExcelReport
{

    public partial class MainViewModel : ViewModelBase
    {
        public string year = "", month = "", day = "", date = "";

        #region======================
        private bool _CanPublish; public bool CanPublish { get { return _CanPublish; } set { _CanPublish = value; OnPropertyChanged("CanPublish", value); } }
        private bool _CanReplan; public bool CanReplan { get { return _CanReplan; } set { _CanReplan = value; OnPropertyChanged("CanReplan", value); } }
        private bool _CanDelete; public bool CanDelete { get { return _CanDelete; } set { _CanDelete = value; OnPropertyChanged("CanDelete", value); } }
        private double _FR01; public double FR01 { get { return _FR01; } set { _FR01 = value; OnPropertyChanged("FR01", value); } }
        private double _WTGFDLGS; public double WTGFDLGS { get { return _WTGFDLGS; } set { _WTGFDLGS = value; OnPropertyChanged("WTGFDLGS", value); } }
        private double _RRWIDTH; public double RRWIDTH { get { return _RRWIDTH; } set { _RRWIDTH = value; OnPropertyChanged("RRWIDTH", value); } }
        private double _NRRWIDTH; public double NRRWIDTH { get { return _NRRWIDTH; } set { _NRRWIDTH = value; OnPropertyChanged("NRRWIDTH", value); } }
        private double _RWGross; public double RWGross { get { return _RWGross; } set { _RWGross = value; OnPropertyChanged("RWGross", value); } }
        private double _NRWGross; public double NRWGross { get { return _NRWGross; } set { _NRWGross = value; OnPropertyChanged("NRWGross", value); } }
        private double _AddWidth; public double AddWidth { get { return _AddWidth; }
            set { 
                _AddWidth = value; 
                SetWastage(_AddWidth);
                OnPropertyChanged("AddWidth", value); }
        }
        
        private double _BASEQTY; public double BASEQTY { get { return _BASEQTY; } set { _BASEQTY = value; OnPropertyChanged("BASEQTY", value); } }
        private double _MQTY; public double MQTY { get { return _MQTY; } set { _MQTY = value; OnPropertyChanged("MQTY", value); } }
        private double _GR01; public double GR01 { get { return _GR01; } set { _GR01 = value; OnPropertyChanged("GR01", value); } }
        private double _GR02; public double GR02 { get { return _GR02; } set { _GR02 = value; OnPropertyChanged("GR02", value); } }
        private double _NGR02; public double NGR02 { get { return _NGR02; } set { _NGR02 = value; OnPropertyChanged("NGR02", value); } }
        private double _NGF02; public double NGF02 { get { return _NGF02; } set { _NGF02 = value; OnPropertyChanged("NGF02", value); } }
        private double _GF01; public double GF01 { get { return _GF01; } set { _GF01 = value; OnPropertyChanged("GF01", value); } }
        private double _GF02; public double GF02 { get { return _GF02; } set { _GF02 = value; OnPropertyChanged("GF02", value); } }
        private string _REMARK; public string REMARK { get { return _REMARK; } set { _REMARK = value; OnPropertyChanged("REMARK", value); } }
         
        //WTGWBBRT
        #endregion
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        public INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }
        public INTEXBL INTEXBL
        {
            get
            {
                return app.INTEXBL;
            }
        }
        private SqlConnection m_SqlServerDB;
        public SqlConnection SqlServerDB
        {
            get
            {
                if (m_SqlServerDB == null)
                {
                    m_SqlServerDB = new SqlConnection(app.SQLDB);
                }
                return m_SqlServerDB;
            }
        }
        private DataRow m_dwVKP = null;
        public DataRow dwVKP
        {
            get
            {
                return m_dwVKP;
            }
            set
            {
                if (value == null)
                    return;
                m_dwVKP = value;
                ABPLFD = "X";
                KRS = dwVKP["VKPAUFKRS"].ToString();
                LFD = dwVKP["VKPAUFLFD"].ToString();
                POS = dwVKP["VKPAUFPOS"].ToString();
                OnPropertyChanged("dwVKP", value);
            }
        }
        #region=============CollectionViewSource===========
        public SETINTEXDB SetEnv
        {
            get;
            set;

        }
        public SETINTEXDB SetDetail
        {
            get;
            set;
        }
        public SETINTEXDB SetMaster
        {
            get;
            set;
        } 
 
        #endregion
        public bool IsAB05 = true;
        public bool IsAB55 = true;
        public bool IsAB45 = true;
        public bool IsAB50 = true;
        public string PlanID = "";
        private string m_LFD;
        public string LFD
        {
            get
            {
                return Helper.Right("000000" + m_LFD, 6);
            }
            set
            {
                m_LFD = value;
                OnPropertyChanged("LFD", value);
            }
        }
        private string m_KRS;
        public string KRS
        {
            get
            {
                return Helper.Right("   " + m_KRS, 2); ;
            }
            set
            {
                m_KRS = value;
                OnPropertyChanged("KRS", value);
            }
        }
        private string m_POS;
        public string POS
        {
            get
            {
                return Helper.Right("000" + m_POS, 3);
            }
            set
            {
                m_POS = value;
                OnPropertyChanged("POS", value);
            }
        }

        SETINTEXDB INTEXDB = new SETINTEXDB();
        public string ABPLFD = "X";
        int ABPOS = 1;
        public double LDAB = 1; 
        string PRLO = "", PRLB = "", PRLP = "";
        string time;
        int ABAID = 1;
        public DataTable tbABAUFM = null;
        string filter = "";
        DataRow[] rows = null;
        public MainViewModel()
            : base()
        {
            if (SetEnv == null)
            {
                SetEnv = new SETINTEXDB();
            }
            if (SetMaster == null)
            {
                SetMaster = new SETINTEXDB();
            }
            if (SetDetail == null)
            {
                SetDetail = new SETINTEXDB();
            }
            _CanDelete = false;
            _CanPublish = false;
            _CanPublish = false;
            /*GF01 = 590.5;
            GF02 = 583;
            GR02 = 1.5;
            NGR02 = 1.5;
            NGF02 = 583;    */      
            Helpers.Helper.GetDate(ref date, ref year, ref month, ref day);
        }
        public DataSet LoadEnv()
        {
            DataSet SResult = new DataSet();
            DataSet SReturn = new DataSet();
            DataRow dwData;
            dwData = INTEXDB.ICC_QUERYTB.NewRow();
            dwData["APKMANDANT"] = app.Mandant;
            SResult = INTEXDBC.QueryAPKOPF(dwData, 1);
            SetEnv.Merge(SResult);
            SResult = INTEXDBC.QueryICC_PRULES(null, 9999);
            SetEnv.Merge(SResult);
            return SReturn;
        }

        private DataSet GetJPattern(string VKP)
        {
            DataSet SResult;
            DataSet SReturn = new System.Data.DataSet();
            try
            {

                SqlCommand sql = SqlServerDB.CreateCommand();
                sql.CommandText = "SELECT * FROM jinling.dbo.排花 WHERE 布号 like '" + VKP + "%'"; ;
                SResult = INTEXDBC.Connect2Proxy(sql);
                if (SResult.Tables.Count > 0)
                {
                    SResult.Tables[0].TableName = "排花";
                }
                SReturn.Merge(SResult);
                sql.CommandText = "SELECT * FROM jinling.dbo.经纬纱 WHERE 布号 like '" + VKP + "%'"; ;
                SResult = INTEXDBC.Connect2Proxy(sql);
                if (SResult.Tables.Count > 0)
                {
                    SResult.Tables[0].TableName = "经纬纱";
                }
                SReturn.Merge(SResult);
                sql.CommandText = "SELECT 布号 As FClothNo, 织造备注1 AS RREMARK1,织造备注2 AS RREMARK2,织造备注3 AS RREMARK3,整经备注1 AS WREMARK1,整经备注2 AS WREMARK2,整经备注3 AS WREMARK3,纬纱单备注1 AS WFREMARK1,纬纱单备注2 AS WFREMARK2,纬纱单备注3  AS WFREMARK3 FROM jinling.dbo.规格表 WHERE 布号 like '" + VKP + "%'"; ;
                SResult = INTEXDBC.Connect2Proxy(sql);
                if (SResult.Tables.Count > 0)
                {
                    SResult.Tables[0].TableName = "TechMaster";
                }
                SReturn.Merge(SResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return SReturn;
        }

        private void GetMaxCones(DataSet db)
        {
            try
            {
                string _delimiter = ",";
                string FClothNo = "";
                string filter = "";
                DataRow 排花 = null;
                string 轴花 = "";
                DataRow[] rows;
                DataRow 经纬纱 = null;
                string 全组轴排花内容 = "";
                string 半组轴排花内容 = "";
                string 排花回数内容 = "";
                DataTable tbBS08 = db.Tables["BASTGA"]; 
                Dictionary<string, int> YarnEnds = new Dictionary<string, int>();
                Dictionary<string, int> BeanYarnEnds = new Dictionary<string, int>(); 
                foreach (DataRow dwBS in db.Tables["BASTGA"].Rows)
                {
                    if (dwBS["BAGBEM"].ToString().Trim() == "±ßÉ´")
                    {
                        dwBS["BAGFILLER"] = "0";
                    }
                }
                foreach (DataRow dwWS in db.Tables["WASTKE"].Rows)
                {
                    FClothNo = dwWS["WAKART"].ToString().Trim() + "-" + dwWS["WAKWCOL"].ToString().Trim();

                    filter = "TRIM(布号)='" + FClothNo + "'";
                    rows = db.Tables["经纬纱"].Select(filter);
                    if (rows.Length == 0)
                    {
                        continue; 
                    }
                    经纬纱 = rows[0];
                    filter = "TRIM(布号)='" + FClothNo + "'";
                    rows = db.Tables["排花"].Select(filter);
                    if (rows.Length == 0)
                    {
                        continue; 
                    }
                    排花 = rows[0];
                    全组轴排花内容 = 排花["全组轴排花内容"].ToString();
                    半组轴排花内容 = 排花["半组轴排花内容"].ToString();
                    排花回数内容 = 排花["排花回数内容"].ToString();
                    string[] 全组轴排花 = 全组轴排花内容.Split(new String[] { _delimiter }, StringSplitOptions.None);
                    string[] 半组轴排花 = 半组轴排花内容.Split(new String[] { _delimiter }, StringSplitOptions.None);
                    string[] 排花回数 = 排花回数内容.Split(new String[] { _delimiter }, StringSplitOptions.None);
                    string[] 轴排花;
                    string[] 纱线列表;
                    int startp = 20;
                    YarnEnds = new Dictionary<string, int>();
                    for (int bm = 0; bm < 20; bm++)
                    {
                        #region====全组轴排花===
                        int cpos = 0;
                        string bx = 全组轴排花[bm];
                        if (bx == "")
                            break;
                        int bn = Convert.ToInt16(bx);
                        string yarnid = "";
                        int ends;
                        int 回数 = Convert.ToInt16(排花回数[bm + 1]);
                        int maxcones = 0;
                        BeanYarnEnds = new Dictionary<string, int>();
                        for (int y = startp; y < startp + bn; y++)
                        {
                            yarnid = 全组轴排花[y];
                            ends = Convert.ToInt16(全组轴排花[y + bn]);
                            if (!BeanYarnEnds.ContainsKey(yarnid))
                            {
                                BeanYarnEnds.Add(yarnid, ends * 回数);
                            }
                            else
                            {
                                BeanYarnEnds[yarnid] = BeanYarnEnds[yarnid] + ends * 回数;
                            }
                        }
                        #endregion
                        #region====半组轴排花======
                        int startpos = 20;
                        int count = 0;
                        if (半组轴排花.Length > 1)
                        {
                            count = Convert.ToInt16(半组轴排花[bm]);
                        }
                        if (count > 0)
                        {
                            for (int iXbm = 0; iXbm < bm; iXbm++)
                            {
                                startpos += Convert.ToInt16(半组轴排花[iXbm]) * 2;

                            }

                            for (int xb = startpos; xb < startpos + count; xb++)
                            {
                                yarnid = 半组轴排花[xb];
                                ends = Convert.ToInt16(半组轴排花[xb + count]);
                                if (!BeanYarnEnds.ContainsKey(yarnid))
                                {
                                    BeanYarnEnds.Add(yarnid, ends * 回数);
                                }
                                else
                                {
                                    BeanYarnEnds[yarnid] = BeanYarnEnds[yarnid] + ends;
                                }
                            }
                        }
                        #endregion
                        startp = startp + 2 * bn;

                        #region====Max Cones======
                        foreach (KeyValuePair<string, int> kp in BeanYarnEnds)
                        {
                            yarnid = kp.Key;
                            if (!YarnEnds.ContainsKey(yarnid))
                            {
                                YarnEnds.Add(yarnid, kp.Value);
                            }
                            else
                            {
                                if (YarnEnds[kp.Key] < BeanYarnEnds[kp.Key])
                                {
                                    YarnEnds[kp.Key] = BeanYarnEnds[kp.Key];
                                }
                            }
                        }
                        string yarn = "";
                        foreach (KeyValuePair<string, int> kp in YarnEnds)
                        {
                            string jwy="经纱代号" + kp.Key.Trim();
                            if (!经纬纱.Table.Columns.Contains(jwy))
                            {
                                MessageBox.Show("出现了错误的纱线代号");
                                continue;
                            }
                            yarn = 经纬纱[jwy].ToString().Trim();
                            var qYarn = from DataRow dwYarn in tbBS08.AsEnumerable()
                                        where dwYarn["BAGGFARBE"].ToString().Trim() == yarn
                                        && dwYarn["BAGART"].ToString().Trim() == dwWS["WAKART"].ToString().Trim()
                                        && dwYarn["BAGFARBE"].ToString().Trim() == dwWS["WAKWCOL"].ToString().Trim()
                                        select dwYarn;
                            foreach (DataRow row in qYarn)
                            {
                                row["BAGFILLER"] = kp.Value;
                            }
                        }
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        public DataSet LoadData(DataRow dwInput)
        {
            DataSet SReturn = new DataSet();
            DataSet SResult = new DataSet();
            string krs = "";
            string lfd = "";
            string MANDANT = "";
            DataRow dwData = null;
            dwData = INTEXDB.ICC_QUERYTB.NewRow();
            try
            {
                krs = dwInput["VKPAUFKRS"].ToString();
                lfd = dwInput["VKPAUFLFD"].ToString();
                MANDANT = dwInput["VKPMANDANT"].ToString();
                SResult = INTEXBL.QueryVKK(MANDANT, krs, lfd);
                if (SResult.Tables[0].Rows.Count == 0)
                    throw new Exception("任务书不存在");
                SReturn.Merge(SResult);
                dwData["WDMANDANT"] = MANDANT;
                dwData["WDAUFKRS"] = krs;
                dwData["WDAUFLFD"] = lfd;
                SResult = INTEXDBC.QueryAPZUORD(dwData, 2);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryAPZUORD(dwData, 3);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryAPZUORD(dwData, 4);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryAPZUORD(dwData, 5);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryWDECK(dwData, 4);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryWASTAMM(dwData, 5);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryWTGEW(dwData, 2);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryWASTKE(dwData, 2);
                SReturn.Merge(SResult);
                dwData["WDSA"] = "C";
                SResult = INTEXDBC.QueryWAFARBEN(dwData, 6);
                SReturn.Merge(SResult);
                dwData["WDSA"] = "B";
                SResult = INTEXDBC.QueryWAFARBEN(dwData, 7);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryWASTGA(dwData, 4);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryBSSATZ(dwData, 2);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryBSGROE(dwData, 2);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryBHSATZ(dwData, 2);
                SReturn.Merge(SResult);
                SResult = INTEXDBC.QueryBASTGA(dwData, 2);
                SReturn.Merge(SResult); 
                dwData["ABPART"] = krs + "-" + Helpers.Helper.Right(lfd, 4).Trim(); 
                SResult = INTEXDBC.QueryICC_ABAX(dwData, 2);
                SReturn.Merge(SResult);
                SReturn.Merge(GetJPattern(krs + "-" + Helpers.Helper.Right(lfd, 4).Trim()));
                GetMaxCones(SReturn);
                DataSet STemp = new System.Data.DataSet();
                if (SReturn.Tables.Contains("APZUORD"))
                {
                    string processed = "";
                    foreach (DataRow rx in SReturn.Tables["APZUORD"].Rows)
                    {
                        string APZANRKRS = rx["APZANRKRS"].ToString();
                        string APZALFDNR = rx["APZALFDNR"].ToString();
                        if (processed.Contains(APZANRKRS + APZALFDNR + ";"))
                            continue;
                        processed += APZANRKRS + APZALFDNR + ";";

                        dwData["APFMANDANT"] = rx["APZMANDANT"];
                        dwData["APFANRKRS"] = APZANRKRS;
                        dwData["APFALFDNR"] = APZALFDNR;
                        SResult = INTEXDBC.QueryAPFOLGE(dwData, 4);
                        STemp.Merge(SResult);

                        dwData["APAKMANDANT"] = rx["APZMANDANT"];
                        dwData["APAKANRKRS"] = APZANRKRS;
                        dwData["APAKALFDNR"] = APZALFDNR;
                        SResult = INTEXDBC.QueryAPARTK(dwData, 1);
                        STemp.Merge(SResult);
                    }
                    SReturn.Merge(STemp);
                }

                STemp = new System.Data.DataSet();
                string yarns = "";
                string Yart = "";
                string Yvar = "";
                if (SReturn.Tables.Contains("WASTGA"))
                {
                    foreach (DataRow row in SReturn.Tables["WASTGA"].Rows)
                    {
                        dwData = INTEXDB.ICC_QUERYTB.NewRow();
                        Yart = row["WAGGART"].ToString();
                        Yvar = row["WAGGVAR"].ToString();
                        if (yarns.Contains(Yart + Yvar + ";"))
                        {
                            continue;
                        }
                        yarns += Yart + Yvar + ";";
                        dwData["GSMANDANT"] = row["WAGMANDANT"];
                        dwData["GSART"] = Yart;
                        dwData["GSVAR"] = Yvar;
                        SResult = INTEXDBC.QueryGSDAT(dwData);
                        STemp.Merge(SResult);
                    }
                    SReturn.Merge(STemp);
                }
                STemp = new System.Data.DataSet();
                if (SReturn.Tables.Contains("BASTGA"))
                {
                    foreach (DataRow row in SReturn.Tables["BASTGA"].Rows)
                    {
                        Yart = row["BAGGART"].ToString();
                        Yvar = row["BAGGVAR"].ToString();
                        if (yarns.Contains(Yart + Yvar + ";"))
                        {
                            continue;
                        }
                        yarns += Yart + Yvar + ";";

                        dwData["GSMANDANT"] = row["BAGMANDANT"];
                        dwData["GSART"] = Yart;
                        dwData["GSVAR"] = Yvar;
                        SResult = INTEXDBC.QueryGSDAT(dwData);
                        STemp.Merge(SResult);
                    }
                    SReturn.Merge(STemp);
                }
                SResult = INTEXDBC.QueryGASTGA(null, 0);
                STemp.Merge(SResult);
                if (SReturn.Tables.Contains("GSDAT"))
                {
                    foreach (DataRow row in SReturn.Tables["GSDAT"].Rows)
                    {
                        dwData["GAGMANDANT"] = row["GSMANDANT"];
                        dwData["GAGART"] = row["GSART"];
                        SResult = INTEXDBC.QueryGASTGA(dwData, 2);
                        STemp.Merge(SResult);
                    }
                    SReturn.Merge(STemp);
                }

                #region============交货范围LIEF===================
                DataTable tbVKK07 = new DataTable();
                string str1 = "", str2 = "";
                string TXTISIND = krs + lfd + "000" + "LIEF";
                var query2 = from dwTemp in SReturn.Tables["ICC_TXTKON"].AsEnumerable()
                             where dwTemp["TXTIPIND"].ToString().Contains(TXTISIND)
                             select dwTemp;
                if (query2.Count() > 0)
                {
                    tbVKK07 = query2.CopyToDataTable();
                }
                string 交货范围 = "";
                string src = "";
                foreach (DataRow dwTXTKON in tbVKK07.Rows)
                {
                    for (int ti = 1; ti < 40; ti++)
                    {
                        string ci = "TXT" + Helpers.Helper.Right("00" + ti, 2) + "0";
                        src = dwTXTKON[ci].ToString(); src = Helper.GetGB2312Value(src).Trim();
                        if (src == "") break;
                        if (!src.Contains("交货范围")) continue;
                        Helper.SplitString(ref src, ref str1, ref str2);
                        交货范围 = str2;
                    }
                }

                #endregion
                string 有效幅宽 = "",幅宽="";
                foreach (DataRow dwVA07 in SReturn.Tables["VAART"].Rows)
                {
                    string vbrt = dwVA07["VAAMEBRT"].ToString().Trim();

                    src = dwVA07["VAABRTVON"].ToString();
                    double v1 = System.Math.Round(System.Convert.ToDouble(src) * 0.01, 0);
                    有效幅宽= v1 + vbrt; 

                    src = dwVA07["VAABRTBIS"].ToString();
                    double v2 = System.Math.Round(System.Convert.ToDouble(src) * 0.01, 0);
                    幅宽= (v2 - 1) + "-" + v2 + vbrt; 
                }
               
                 
                #region============组织规格VAD===================
                foreach (DataRow row in SReturn.Tables["VKPOS"].Rows)
                {
                    string koll = row["VKPKOLL"].ToString();
                    string art = row["VKPART"].ToString();
                    string text = "";
                    string 规格 = "";
                    TXTISIND = koll + art.Trim();
                    var qvad = from dwTemp in SReturn.Tables["ICC_TXTKON"].AsEnumerable()
                               where dwTemp["TXTIPIND"].ToString().Trim() == TXTISIND
                               select dwTemp;
                    if (qvad.Count() > 0)
                    {
                        tbVKK07 = qvad.CopyToDataTable();
                    }
                    foreach (DataRow dwTXTKON in tbVKK07.Rows)
                    {
                        for (int ti = 1; ti < 40; ti++)
                        {
                            string ci = "TXT" + Helpers.Helper.Right("00" + ti, 2) + "0";
                            src = dwTXTKON[ci].ToString(); src = Helper.GetGB2312Value(src).Trim();
                            if (src == "")
                                break;
                            text += src;
                        }
                    }
                    规格 = text;
                    row["OVERSHORT"] =Helper.ConvertGB2312To8859P1(交货范围);
                    row["CONSTRUCTION"] = 规格 + ",幅宽:" + 幅宽;
                }
                #endregion
                SetDetail.Clear();
                SetMaster.Clear();
                SetMaster.Merge(SReturn);
                SetEnv.Tables["ICC_ABAX"].Clear();
                SetEnv.Merge(SetDetail.Tables["ICC_ABAX"]);
                tbABAUFM = SetMaster.Tables["ICC_ABAX"].Clone();
                tbABAUFM.TableName = "ICC_ABAX";
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询遇到错误，请核对任务书编号"+ex.Message);
                Tracer.Error(ex.StackTrace, ex);
            }

            return SReturn;
        }

        public bool FilterData()
        {
            SetDetail.Clear();
            bool result = false;
            string ART = "", COLOR = "", VAR = "", FINISH = "";
            DataTable tb;
            try
            {

                ART = Helpers.Helper.Left(dwVKP["VKPART"].ToString().PadRight(20), 20);
                COLOR = Helpers.Helper.Left(dwVKP["VKPFARBE"].ToString().PadRight(10), 10);
                #region===判断是否已经创建生产单=======
                var query = from DataRow ABPOS in SetMaster.Tables["ABPOS"].AsEnumerable()
                            from DataRow ABAX in SetMaster.Tables["ICC_ABAX"].AsEnumerable()
                            where ABPOS["ABPAUFKRS"].ToString() == ABAX["ABAAUFKRS"].ToString()
                            && ABPOS["ABPAUFLFD"].ToString() == ABAX["ABAAUFLFD"].ToString()
                            && ABPOS["ABPAUFPOS"].ToString() == ABAX["ABAAUFPOS"].ToString()
                            && ABAX["EXART"].ToString().Trim() == KRS + "-" + Helpers.Helper.Right(LFD, 4) + "-" + Helper.Right(POS, 3)
                            select ABPOS;
                if (query.Count() > 0)
                {
                    tb = query.CopyToDataTable();
                    tb.TableName = "ABPOS";
                    SetDetail.Merge(tb);
                }
                ResetUI();
              

                filter = "EXART LIKE '" + KRS + "-" + Helpers.Helper.Right(LFD, 4) + "-" + Helper.Right(POS, 3) + "%'";
                rows = SetMaster.Tables["ICC_ABAX"].Select(filter);

                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "ICC_ABAX";
                    SetDetail.Merge(tb);
                    SetEnv.Tables["ICC_ABAX"].Clear();
                    SetEnv.Merge(SetDetail.Tables["ICC_ABAX"]);
                    //MessageBox.Show("生产单已经创建完毕，请去生产单处理界面查看");
                    result = true;
                }
                #endregion
                #region=== 档案信息=======
               
                filter = "VKPAUFKRS='" + KRS + "' AND VKPAUFLFD='" + LFD + "' AND VKPAUFPOS='" + POS + "'";
                rows = SetMaster.Tables["VKPOS"].Select(filter);
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "VKPOS";
                    SetDetail.Merge(tb);
                }
                filter = "WDAUFKRS='" + KRS + "' AND WDAUFLFD='" + LFD + "' AND WDAUFPOS='" + POS + "'";
                rows = SetMaster.Tables["WTGEW"].Select(filter);
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "WTGEW";
                    SetDetail.Merge(tb);
                }
                if (SetMaster.Tables.Contains("APFOLGE"))
                {
                    SetDetail.Merge(SetMaster.Tables["APFOLGE"]);
                }
                if (SetMaster.Tables.Contains("WAFARBEN"))
                {
                    filter = "WAFART='" + ART + "' AND WAFZUSATZ='" + COLOR + "'";
                    rows = SetMaster.Tables["WAFARBEN"].Select(filter);
                    if (rows.Length > 0)
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "WAFARBEN";
                        SetDetail.Merge(tb);
                    }
                }
                if (SetMaster.Tables.Contains("WASTKE"))
                {
                    filter = "WAKART='" + ART + "' AND WAKWCOL='" + COLOR + "'";
                    rows = SetMaster.Tables["WASTKE"].Select(filter);
                    if (rows.Length > 0)
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "WASTKE";
                        SetDetail.Merge(tb);
                    }
                }
                if (SetMaster.Tables.Contains("BSGROE"))
                {
                    filter = "BSGART='" + ART + "'";
                    rows = SetMaster.Tables["BSGROE"].Select(filter);
                    if (rows.Length > 0)
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "BSGROE";
                        SetDetail.Merge(tb);
                    }
                }
                if (SetMaster.Tables.Contains("BSSATZ"))
                {
                    filter = "BSKART='" + ART + "'";
                    rows = SetMaster.Tables["BSSATZ"].Select(filter);
                    if (rows.Length > 0)
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "BSSATZ";
                        SetDetail.Merge(tb);
                    }
                }
                if (SetMaster.Tables.Contains("WASTGA"))
                {
                    filter = "WAGART='" + ART + "' AND WAGWCOL='" + COLOR + "'";
                    rows = SetMaster.Tables["WASTGA"].Select(filter);
                    if (rows.Length > 0)
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "WASTGA";
                        SetDetail.Merge(tb);
                    }
                    else
                    {
                        MessageBox.Show("请核对纬纱工艺");

                    }
                }
                if (SetMaster.Tables.Contains("BASTGA"))
                {
                    filter = "BAGART='" + ART + "' AND BAGFARBE='" + COLOR + "'";
                    string sort = "BAGPOS ASC";
                    rows = SetMaster.Tables["BASTGA"].Select(filter,sort);
                    if (rows.Length > 0)
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "BASTGA";
                        SetDetail.Merge(tb);
                    }
                    else
                    {
                        MessageBox.Show("请核对经纱工艺");
                        return false;
                    }
                }
                if (SetMaster.Tables.Contains("GASTGA"))
                {
                    SetDetail.Merge(SetMaster.Tables["GASTGA"]);
                }
                else
                {
                    MessageBox.Show("对应纱线无原纱需求，请确认");
                    return false;

                }
                if (SetMaster.Tables.Contains("BHSATZ"))
                {
                    filter = "BHKART='" + ART + "'";
                    rows = SetMaster.Tables["BHSATZ"].Select(filter);
                    if (rows.Length > 0)
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "BHSATZ";
                        SetDetail.Merge(tb);
                    }
                    else
                    {
                        MessageBox.Show("请核对经纱工艺");
                        return false;
                    }
                }

                if (SetMaster.Tables.Contains("GSDAT"))
                {
                    SetDetail.Merge(SetMaster.Tables["GSDAT"]);
                }
                #endregion
                             
                #region=== 工艺验证=======
                filter = "WDAUFKRS='" + dwVKP["VKPAUFKRS"].ToString() + "' AND WDAUFLFD='"
                   + dwVKP["VKPAUFLFD"].ToString() + "' AND WDAUFPOS='" + dwVKP["VKPAUFPOS"].ToString() + "' AND WDSA='K' AND WDUPOS='00'";
                rows = SetMaster.Tables["WDECK"].Select(filter);
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "WDECK";
                    foreach (DataRow dwData in tb.Rows)
                    {
                        ART = dwData["WDART"].ToString();
                        VAR = dwData["WDVAR"].ToString();
                        COLOR = dwData["WDFARBE"].ToString();
                        FINISH = dwData["WDBESCHICH"].ToString();
                        result = INTEXBL.ValidateArticle("F", ART, VAR, COLOR, FINISH, SetMaster);
                        if (!result)
                        {
                            return result;
                        }
                    }
                    SetDetail.Merge(tb);
                }
                filter = "WDAUFKRS='" + dwVKP["VKPAUFKRS"].ToString() + "' AND WDAUFLFD='" + dwVKP["VKPAUFLFD"].ToString()
                + "' AND WDAUFPOS='" + dwVKP["VKPAUFPOS"].ToString() + "'  AND WDSA='K' AND WDUPOS='00'";
                rows = SetMaster.Tables["WASTAMM"].Select(filter);
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "WASTAMM";
                    foreach (DataRow dwData in tb.Rows)
                    {
                        ART = dwData["WAART"].ToString();
                        VAR = dwData["WAVAR"].ToString();
                        result = INTEXBL.ValidateArticle("R", ART, VAR, "", "", SetMaster);
                        if (!result)
                        {
                            return result;
                        }
                    }
                    SetDetail.Merge(tb);
                }
                foreach (DataRow row in SetMaster.Tables["WASTAMM"].Rows)
                {
                    ART = row["WAART"].ToString();
                    VAR = row["WAVAR"].ToString();
                    filter = "APZART='" + ART + "' AND APZSTUFE='F' ";
                    rows = SetMaster.Tables["APZUORD"].Select(filter);
                    if (rows.Length == 0)
                    {

//                        MessageBox.Show("请指定后整理流程");
  //                      return false;
                        DataRow dwAPZ = INTEXBL.CreateAPZ("F", ART, VAR);
                        SetMaster.Tables["APZUORD"].Rows.Add().ItemArray = dwAPZ.ItemArray;
                    }
                    else
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "APZUORD";
                        SetDetail.Merge(tb);
                    }
                    filter = "APZART='" + row["WAART"].ToString() + "' AND APZSTUFE='R' ";
                    rows = SetMaster.Tables["APZUORD"].Select(filter);
                    if (rows.Length == 0)
                    {

                        //MessageBox.Show("请指定织造流程");
                        //return false;
                        DataRow dwAPZ = INTEXBL.CreateAPZ("R", ART, VAR);
                        SetMaster.Tables["APZUORD"].Rows.Add().ItemArray = dwAPZ.ItemArray;
                    }
                    else
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "APZUORD";
                        SetDetail.Merge(tb);
                    }
                }
                foreach (DataRow row in SetMaster.Tables["WASTKE"].Rows)
                {
                    ART = row["WAKKART"].ToString();
                    VAR = row["WAKKVAR"].ToString();
                    COLOR = row["WAKKFARBE"].ToString();
                    result = INTEXBL.ValidateArticle("K", ART, VAR, COLOR, "", SetMaster);
                    if (!result)
                    {
                        return false;
                    }

                    filter = "APZART='" + row["WAKKART"].ToString() + "' AND APZSTUFE='K' ";
                    rows = SetMaster.Tables["APZUORD"].Select(filter);
                    if (rows.Length == 0)
                    {
                        //result = false;
                        //MessageBox.Show("请指定浆纱流程");
                        //return result;
                        DataRow dwAPZ = INTEXBL.CreateAPZ("K", ART, VAR);
                        SetMaster.Tables["APZUORD"].Rows.Add().ItemArray = dwAPZ.ItemArray;
                    }
                    else
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "APZUORD";
                        SetDetail.Merge(tb);
                    }
                }
                foreach (DataRow row in SetMaster.Tables["WASTGA"].Rows)
                {
                    ART = row["WAGGART"].ToString();
                    VAR = row["WAGGVAR"].ToString();
                    COLOR = row["WAGGFARBE"].ToString();
                    result = INTEXBL.ValidateArticle("G", ART, VAR, COLOR, "", SetMaster);
                    if (!result)
                    {
                        return result;
                    }
                    filter = "APZART='" + row["WAGGART"].ToString() + "' ";
                    rows = SetMaster.Tables["APZUORD"].Select(filter);
                    if (rows.Length == 0)
                    {
                        //result = false;
                        //MessageBox.Show("请指定染色流程");
                        DataRow dwAPZ = INTEXBL.CreateAPZ("G", ART, VAR);
                        SetMaster.Tables["APZUORD"].Rows.Add().ItemArray = dwAPZ.ItemArray;
                    }
                    else
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "APZUORD";
                        SetDetail.Merge(tb);
                    }
                }
                foreach (DataRow row in SetMaster.Tables["BASTGA"].Rows)
                {
                    ART = row["BAGGART"].ToString();
                    VAR = row["BAGGVAR"].ToString();
                    COLOR = row["BAGGFARBE"].ToString();
                    result = INTEXBL.ValidateArticle("G", ART, VAR, COLOR, "", SetMaster);
                    if (!result)
                    {
                        return result;
                    }
                    filter = "APZART='" + row["BAGGART"].ToString() + "' ";
                    rows = SetMaster.Tables["APZUORD"].Select(filter);
                    if (rows.Length == 0)
                    {
                        result = false;
                        MessageBox.Show("请指定染色流程");
                        DataRow dwAPZ = INTEXBL.CreateAPZ("G", ART, VAR);
                        SetMaster.Tables["APZUORD"].Rows.Add().ItemArray = dwAPZ.ItemArray;
                    }
                    else
                    {
                        tb = rows.CopyToDataTable();
                        tb.TableName = "APZUORD";
                        SetDetail.Merge(tb);
                    }
                }

                #endregion 
            
                string ENDD = dwVKP["VKPLIEFTERM"].ToString();
                if (ENDD.Trim() == "0")
                {
                    result = false;
                    MessageBox.Show("销售单交期未指定");
                    return result;
                }

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return result;
        }

        private void ResetUI()
        {
            try
            {
                foreach (DataRow row in SetDetail.Tables["ICC_ABAX"].Rows)
                {
                    string ABAWAKZ = row["ABAWAKZ"].ToString();
                    switch (ABAWAKZ)
                    {
                        case "S":
                            break;
                        case "F":
                            //DAB05 = row["DELDATE"].ToString();
                            break;
                        case "R":
                            //DAB55 = row["DELDATE"].ToString();
                            break;
                        case "W":
                            //DAB45 = row["DELDATE"].ToString();
                            break;
                        case "K":
                            break;
                        case "G":
                            //DAB50 = row["DELDATE"].ToString();
                            break;
                        case "B":
                            //DAB50 = row["DELDATE"].ToString();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        public void SetWastage(double wastage)
        {
            RWGross = _NRRWIDTH + wastage;
            foreach (DataRow row in SetDetail.Tables["WASTGA"].Rows)
            {
                double WAGABF = Convert.ToDouble(row["WAGABF"].ToString());
                if (WAGABF == 0)
                {
                    row["WAGABF"] = RWGross;
                }
            } 
        }
    }
}